import { ref, reactive, onMounted, type Ref, shallowRef } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { PartitionItem } from "./type/partitionTypes";
import { h } from "vue";
import partitionForm from "../componentsForm/partitionForm.vue";
import { setOriginalFormId, setTenantId } from "./rule/partitionRules";
import { handleTree } from "@/utils/tree";
import { useDataSyncStore } from "@/store/modules/dataSync";

// 设备检测
function deviceDetection() {
  return window.innerWidth <= 1024;
}

export function usePartitionTable(
  tableRef: Ref,
  lesseeId: number,
  tenantName: string,
  dealerId: number,
  dealerName: string
) {
  const form = reactive({
    name: "",
    channelId: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = shallowRef();
  const dataList = ref<PartitionItem[]>([]);
  const treeData = ref<PartitionItem[]>([]); // 用于存储树形结构数据
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });

  // 列表列定义
  const columns = [
    /* {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    }, */
    {
      label: "分区名称",
      prop: "Name",
      width: 180,
      align: "left",
      // 使用scoped slot来渲染树形结构
      slotName: "treeName"
    },
    /* {
      label: "所属经销商",
      prop: "DealerName",
      minWidth: 100
    },
    {
      label: "所属租户",
      prop: "TenantName",
      minWidth: 100
    }, */
    {
      label: "备注",
      prop: "Comment",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "CreateTime",
      minWidth: 160,
      formatter: (row: any) => {
        if (row.CreateTime) {
          return row.CreateTime.replace('T', '/').replace(/\.\d{3}Z?$/, '');
        }
        return row.CreateTime;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];

  // 获取、搜索分区列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      tenantId: lesseeId
    };

    http
      .get(changeHttpLink("/api/Zone"), {
        params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items || [];
          pagination.total = res.Data.TotalCount || 0;
          // 转换为树形结构并计算正确的Level
          const treeResult = handleTree(
            dataList.value,
            "Id",
            "ParentZoneId",
            "children"
          );
          // 递归设置正确的Level值
          const setCorrectLevel = (nodes: any[], level: number = 1) => {
            nodes.forEach(node => {
              node.Level = level;
              if (node.children && node.children.length > 0) {
                setCorrectLevel(node.children, level + 1);
              }
            });
          };
          setCorrectLevel(treeResult);
          treeData.value = treeResult;
          console.log(treeData.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 新增、修改分区
  // 在 openDialog 函数中修改 formData 创建部分
  function openDialog(title: string, row: any = null) {
    const id = row?.Id ?? 0;
    setOriginalFormId(id);
    setTenantId(lesseeId);
    const formData = {
      id: row?.Id ?? 0,
      name: row?.Name ?? "",
      dealerId: dealerId,
      dealerName: dealerName,
      tenantId: lesseeId,
      tenantName: tenantName,
      comment: row?.Comment ?? "",
      parentZoneId: row?.ParentZoneId ?? 0,
      level: row?.Level ?? 1 // 添加 level 属性，默认为1级
    };
    addDialog({
      title: `${title}区域`,
      props: {
        formInline: formData,
        title: title
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(partitionForm, {
          ref: formRef,
          formInline: formData,
          title: title
        }),
      beforeSure: (done, { options: _options }) => {
        const FormRef = formRef.value.getRef();
        // 使用getFormData方法获取最新的表单数据
        const curData = formRef.value.getFormData();
        console.log(curData);
        function chores() {
          message(`您${title}了分区ID为【${curData.id}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
          // 通知全局数据更新
          const dataSyncStore = useDataSyncStore();
          dataSyncStore.notifyZoneDataUpdated();
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData
            };
            console.log("区域新增表单", formData);

            if (title === "创建") {
              delete formData.id;
              http
                .post(changeHttpLink("/api/Zone"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/Zone/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除分区
  function handleDelete(row: PartitionItem) {
    ElMessageBox.confirm(
      `是否确认删除分区ID为${row.Id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        // 先检查分区是否绑定了用户、频道或设备
        getPartitionData(row.Id);
        console.log(row.Id);
        checkPartitionBindings(row.Id)
          .then(canDelete => {
            if (canDelete.allowed) {
              // 可以删除，执行删除操作
              loading.value = true;
              http
                .request("delete", changeHttpLink(`/api/Zone/${row.Id}`), {
                  data: row.Id
                })
                .then((res: any) => {
                  loading.value = false;
                  if (res.Success) {
                    message(`您删除了分区ID为${row.Id}的这条数据`, {
                      type: "success"
                    });
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              // 不能删除，显示提示信息
              message(canDelete.message, { type: "warning" });
            }
          })
          .catch(err => {
            message("检查分区绑定状态失败: " + err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        // 先检查所有选中分区的绑定状态
        const checkPromises = listIds.map(id => checkPartitionBindings(id));

        Promise.all(checkPromises)
          .then(results => {
            const blockedItems = [];
            const allowedIds = [];

            results.forEach((result, index) => {
              if (!result.allowed) {
                const partition = curSelected[index];
                blockedItems.push(`分区"${partition.Name}"：${result.message}`);
              } else {
                allowedIds.push(listIds[index]);
              }
            });

            if (blockedItems.length > 0) {
              // 有分区不能删除，显示提示信息
              const blockedMessage = blockedItems.join("\n");
              if (allowedIds.length > 0) {
                ElMessageBox.confirm(
                  `以下分区无法删除：\n${blockedMessage}\n\n是否继续删除其余${allowedIds.length}个分区？`,
                  "删除确认",
                  {
                    confirmButtonText: "继续删除",
                    cancelButtonText: "取消",
                    type: "warning",
                    draggable: true
                  }
                )
                  .then(() => {
                    // 执行部分删除
                    executeBatchDelete(allowedIds);
                  })
                  .catch(() => {
                    // 取消操作
                  });
              } else {
                // 所有分区都不能删除
                message(`无法删除选中的分区：\n${blockedMessage}`, {
                  type: "warning"
                });
              }
            } else {
              // 所有分区都可以删除
              executeBatchDelete(allowedIds);
            }
          })
          .catch(err => {
            message("检查分区绑定状态失败: " + err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 执行批量删除操作
  function executeBatchDelete(ids: number[]) {
    loading.value = true;
    http
      .post(changeHttpLink("/api/Zone/batch-delete"), {
        data: { ids }
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          message(`已删除选中的${ids.length}条数据`, {
            type: "success"
          });
          tableRef.value.getTableRef().clearSelection();
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 多选框变化
  function handleSelectionChange(val: PartitionItem[]) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  //获取分区频道/用户//api/Dealer/{id}/statistics
  function getPartitionData(zoneId: number) {
    //获取用户数据
    const params = {
      PageSize: 1000,
      PageIndex: 1
    };
    http
      .get(changeHttpLink(`/api/Zone/${zoneId}/users`), { params })
      .then((res: any) => {
        if (res.Success) {
          const userData = res.Data.Items;
          console.log(userData);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
    http
      .get(changeHttpLink(`/api/Zone/${zoneId}/statistics`), { params })
      .then((res: any) => {
        if (res.Success) {
          const statistics = res.Data;
          console.log(statistics);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
    //获取频道数据
    http
      .get(changeHttpLink(`/api/Zone/${zoneId}/channels`), { params })
      .then((res: any) => {
        if (res.Success) {
          const channelData = res.Data.Items;
          console.log(channelData);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
    //获取设备数据
    http
      .get(changeHttpLink(`/api/Zone/${zoneId}/devices`), { params })
      .then((res: any) => {
        if (res.Success) {
          const deviceData = res.Data.Items;
          console.log(deviceData);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  // 检查分区绑定状态
  function checkPartitionBindings(
    zoneId: number
  ): Promise<{ allowed: boolean; message: string }> {
    return new Promise((resolve, reject) => {
      const params = {
        PageSize: 1000,
        PageIndex: 1
      };

      const promises = [
        http.get(changeHttpLink(`/api/Zone/${zoneId}/users`), { params }),
        http.get(changeHttpLink(`/api/Zone/${zoneId}/channels`), { params }),
        http.get(changeHttpLink(`/api/Zone/${zoneId}/devices`), { params })
      ];

      Promise.all(promises)
        .then(([userRes, channelRes, deviceRes]) => {
          const bindingTypes = [];

          // 检查用户绑定
          if (
            userRes.Success &&
            userRes.Data.Items &&
            userRes.Data.Items.length > 0
          ) {
            bindingTypes.push("用户");
          }

          // 检查频道绑定
          if (
            channelRes.Success &&
            channelRes.Data.Items &&
            channelRes.Data.Items.length > 0
          ) {
            bindingTypes.push("频道");
          }

          // 检查设备绑定
          if (
            deviceRes.Success &&
            deviceRes.Data.Items &&
            deviceRes.Data.Items.length > 0
          ) {
            bindingTypes.push("设备");
          }

          if (bindingTypes.length > 0) {
            const message = `此分区已绑定${bindingTypes.join("/")}`;
            resolve({ allowed: false, message });
          } else {
            resolve({ allowed: true, message: "" });
          }
        })
        .catch(err => {
          reject(err);
        });
    });
  }
  onMounted(() => {
    // 初始化加载数据
    onSearch();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    treeData, // 返回树形数据用于表格显示
    selectedNum,
    pagination,
    deviceDetection,
    onSearch,
    getPartitionData,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
